from django.contrib import messages
from django.shortcuts import render,get_object_or_404
from app01.models import Product

new*
def add_products(r):
    name="name"
    price=1.23
    description="desc"
    Product.objects.create(name=name,price=price,description=description)
    return redirect("/get_product")


def product_list(request):
    pl = Product.objects.all()
    return render(request, 'products_list.html', {'pl_收到': products})


def product_detail(request, pk):
    product = get_object_or_404(Product, pk=pk)
    return render(request, 'products_detail.html', {'product': product})


def product_create(request):
    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        description = request.POST.get('description')
        Product.objects.create(name=name, price=price, description=description)
        messages.success(request, 'Product created successfully.')
        return redirect('product_list')
    return render(request, 'products/product_form.html')


def product_update(request, pk):
    product = get_object_or_404(Product, pk=pk)
    if request.method == 'POST':
        name = request.POST.get('name')
        price = request.POST.get('price')
        description = request.POST.get('description')
        product.name = name
        product.price = price
        product.description = description
        product.save()
        messages.success(request, 'Product updated successfully.')
        return redirect('product_detail', pk=product.pk)
    return render(request, 'products/product_form.html', {'product': product})


def product_delete(request, pk):
    product = get_object_or_404(Product, pk=pk)
    if request.method == 'POST':
        product.delete()
        messages.success(request, 'Product deleted successfully.')
        return redirect('product_list')
    return render (request, 'products/product_delete_confirm.html', {'product': product})